# pip install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
import numpy as np
import pickle
from sklearn.metrics import ConfusionMatrixDisplay

# 数据准备
df = pd.read_csv(".\\data\\table8_1.csv", header=0)

# 标签编码
from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()
df["考试成绩等第"] = le.fit_transform(df["考试成绩等第"])
# 划分训练集和测试集
X = df[["每天平均学习时长", "每天平均运动时长", "每天平均游戏时长"]]
y = df["考试成绩等第"]
print(le.classes_)
print(y)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# # 模型训练
# model = RandomForestClassifier(n_estimators=100)
# model.fit(X_train, y_train)
# # 保存模型

# with open("model.pkl", "wb") as f:
#     pickle.dump(model, f)

model = pickle.load(open("model.pkl", "rb"))
# 模型预测
y_pred = model.predict(X_test)

cm = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(cm)
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.figure(figsize=(8, 6))
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=le.classes_)
disp.plot(cmap="Blues")
plt.title("学生成绩等级分类混淆矩阵")
plt.show()

# 输出分类报告
print(y_test)
print(y_pred)
print(model.predict(np.array([[10, 3.5, 1]])))
print(model.predict(np.array([[0.1, 0.5, 10]])))
print(classification_report(y_test, y_pred))

print("训练集的准确度", np.mean(model.predict(X_train) == y_train))
print("测试集的准确度", np.mean(model.predict(X_test) == y_test))

print("训练集的准确度", model.score(X_train, y_train))
print("测试集的准确度", model.score(X_test, y_test))
